import type { FunctionOption, MenuTree } from "@/api/auth/typing";
import router from "./index";
import type { RouteRecordRaw } from "vue-router";

const modules = import.meta.glob("../views/**/*.vue");

/**删除动态生成的路由 */
export const removeDynamicRoute = () => {
  // const routes = router.getRoutes();
  // 想好再做
};

/**根据菜单树生成路由 */
export const generate = (menus: MenuTree) => {
  // 删除之前生成的路由
  removeDynamicRoute();
  // 需要添加的功能
  const functions = findFns(menus);
  const dynamicRoute: RouteRecordRaw = {
    path: "/",
    component: () => import("@/layout/layouts/index.vue"),
    redirect: functions[0]?.accessPath,
    children: [],
  };
  for (const item of functions) {
    dynamicRoute.children.push({
      path: item.accessPath,
      name: item.functionCode,
      component:
        modules[/* @vite-ignore */ "../views" + item.component + ".vue"] ||
        (() => import("@/views/exception/404.vue")),
      meta: {
        permissions: item.permissions,
      },
    });
  }
  const [fn] = functions;
  if (fn) {
    dynamicRoute.redirect = fn.accessPath;
  }
  router.addRoute(dynamicRoute);
  router.addRoute({
    path: "/:pathMatch(.*)*",
    name: "NotFound",
    component: () => import("@/views/exception/404.vue"),
  });
};

/**递归查找菜单树所有功能 */
export const findFns = (menus: MenuTree) => {
  const functions: FunctionOption[] = [];
  for (const item of menus) {
    if ("functionId" in item) {
      functions.push(item);
    } else if ("menuId" in item) {
      functions.push(...item.functions);
      functions.push(...findFns(item.menus));
    }
  }
  return functions;
};
